<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in Employess" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="toAdd">确定</el-button>
      <el-button size="small" @click="$emit('cose')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployess } from '@/api/employess'
import { addDepartments, getDepartmentsDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    orginList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 效验部门编码的唯一性  使用自定义规则效验
    const validCode = (rule, value, callback) => {
      // console.log(value, 'value')
      // console.log(this.orginList)
      let newCode = this.orginList.map(item => item.code)
      // 编辑情况下 先删除自己的编码
      // console.log(newCode)
      if (this.isEdit) {
        newCode = this.orginList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (newCode.includes(value)) {
        // 存在 抛出错误  提示用户编码存在
        callback(new Error(`部门编码 ${value} 已存在`))
      } else {
        callback()
      }
    }
    // 效验部门名称的唯一性  使用自定义规则效验
    const validName = (rule, value, callback) => {
      console.log(value, 'value')
      console.log(this.orginList)
      let newName = this.orginList.filter(item => item.pid === this.id).map(item => item.name)

      if (this.isEdit) {
        const curDepartment = this.orginList.find(item => item.id === this.id)
        // console.log(curDepartment)
        const pid = curDepartment.pid
        const brothers = this.orginList.filter(item => item.pid === pid)
        newName = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      console.log(newName)
      if (newName.includes(value)) {
        // 存在 抛出错误  提示用户编码存在
        callback(new Error(`部门名称 ${value} 已存在`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1~50字符', trigger: 'blur' }

        ]
      },
      Employess: [] // 存放员工信息
    }
  },
  // 方法三 解决数据不更新的问题，使用watch监听id
  // watch: {
  //   // 'id': function(newval, oldval) {
  //   //   console.log(newval, oldval)
  //   //   this.lodaDepartmentsDetail()
  //   // }
  //   'id': {
  //     handler: function(newval, oldval) {
  //       console.log(newval, oldval)
  //       this.lodaDepartmentsDetail()
  //     },
  //     deep: true, // 开启深度监听
  //     immediate: true // 组件家族就立即执行
  //   }
  // },
  created() {
    this.lodaEmployess()
    // 点击的是编辑才调用函数
    if (this.isEdit) {
      this.lodaDepartmentsDetail()
    }
  },
  methods: {
    // 表单重置
    restForm() {
      this.$refs.deptForm.resetFields()
    },
    toAdd() {
      // 兜底效验，暂时假设效验通过
      // 调用函数 添加部门
      // this.Submit()
      // 判断点击的是添加还是编辑部门
      this.$refs.deptForm.validate(valid => {
        if (!valid) return // 效验失败
        this.isEdit ? this.doEdit() : this.Submit()
      })
    },
    // 编辑部门
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 子传父
        this.$emit('Success')
      } catch (error) {
        console.log(error)
      }
    },
    // 根据id获取指定部门的信息
    async lodaDepartmentsDetail() {
      try {
        const res = await getDepartmentsDetail(this.id)
        // console.log(res)
        this.form = res.data
      } catch (error) {
        console.dir(error)
      }
    },
    // 新增部门
    async Submit() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 子传父
        this.$emit('Success')
      } catch (error) {
        this.$message.error(error)
      }
    },
    async lodaEmployess() {
      try {
        const res = await getEmployess()
        // console.log(res)
        this.Employess = res.data
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

